/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.drypisy;

import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/**
 * Controler class. Bridge between GUI and ImagePanel class.
 * @author Marcin
 */
public class AppControler {
    private ImageProcess proc;
    private BufferedImage image;
    private BufferedImage imageOrg;
    private ImagePanel panel;
    private AppGui gui;
    
    /**
     * Constructor.
     * @param pan reference to ImagePanel
     * @param app reference to GUI object
     */
    public AppControler(ImagePanel pan, AppGui app){
        panel = pan;
        gui = app;
    }
    /**
     * 
     * @param p chosen proces object
     */
    public void setProcess(ImageProcess p){
        proc = p;
    }
    /**
     * Run process on actual image and paint results.
     */
    public void process(){
        image = proc.process(image);
        panel.setImage(image);
        gui.repaint();
    }
    /**
     * Returns dimension of image.
     * @return Image dimension.
     */
    public Dimension getImageDimension(){
        return new Dimension(image.getWidth(), image.getHeight());
    }
    /**
     * Return image.
     * @return 
     */
    public BufferedImage getImage(){
        return image;
    }
    /**
     * Load image from file.
     * @param f File which content image.
     */
    public void loadImage(File f){
        try {
            image = ImageIO.read(f);
            imageOrg = ImageIO.read(f);
            panel.setImage(image);
        } catch (IOException ex) {
            Logger.getLogger(AppControler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    /**
     * Save image in file.
     * @param path Path to file
     * @param form File format (jpg, gif, png...)
     */
    public void saveImage(String path, String form){
        try {
            path += "." + form;
            ImageIO.write(image, form, new File(path));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * Undo all changes made on image.
     */
    public void backToOriginalImg(){
        ColorModel cm = imageOrg.getColorModel();
        boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
        WritableRaster raster = imageOrg.copyData(null);
        image =  new BufferedImage(cm, raster, isAlphaPremultiplied, null);
        panel.setImage(image);
        gui.repaint();
    }
}